import { Component, OnInit } from '@angular/core';
import { QuestionType } from '../../shared/models/question.model';
import { QuestionnaireModel, QuestionnaireState } from '../../shared/models/questionnaire.model';
import { QuestionnaireService } from '../../core/services/questionnaire.service';
import { Router, ActivatedRoute } from '@angular/router';



@Component({
  selector: 'qn-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.css']
})
export class EditComponent implements OnInit {
  private questionnaire: QuestionnaireModel;
  private id: string;

  constructor(private questionnaireService: QuestionnaireService,
              private route: ActivatedRoute,
              private router: Router) {
    this.questionnaire = {
      title: '',
      starter: '',
      ending: '',
      state: QuestionnaireState.Created,
      questionList: []
    };
  }

  onAddQuestion(type: QuestionType) {
    // 添加问题到问卷的问题列表
    switch (type) {
      case QuestionType.Text:
      case QuestionType.Score:
        this.questionnaire.questionList.push({
          title: '问题标题',
          type: type,
          answer: ''
        });
        break;
      case QuestionType.SingleSelect:
        this.questionnaire.questionList.push({
          title: '问题标题',
          type: type,
          options: [{'key': 0, 'value': '选项1'}],
          answer: ''
        });
        break;
      case QuestionType.MultiSelect:
        this.questionnaire.questionList.push({
          title: '问题标题',
          type: type,
          options: [{'key': 0, 'value': '选项1'}],
          answer: {}
        });
        break;
      default:
        break;
    }
  }

  ngOnInit(): void {
    const id = this.route.snapshot.paramMap.get('id');
    if (this.id && this.id !== '0') {
      this.questionnaireService.getQuestionnaireById(id)
        .subscribe(
          questionnaire => this.questionnaire = questionnaire,
          error => console.log(error)
        );
    }
  }


  onSubmitQuestionnaire(questionnaire: QuestionnaireModel) {
    if (questionnaire.state === QuestionnaireState.Created) {
      if (this.id && this.id !== '0') {
        this.questionnaireService.updateQuestionnaire(questionnaire)
          .subscribe(
            // tslint:disable-next-line:no-shadowed-variable
            questionnaire => this.gotoCenter(),
            error => console.log(error)
          );
      } else {
        this.questionnaireService.addQuestionnaire(questionnaire)
          .subscribe(
            // tslint:disable-next-line:no-shadowed-variable
            questionnaire => this.gotoCenter(),
            error => console.log(error)
          );
      }
    }
  }

  gotoCenter() {
    this.router.navigateByUrl('/');
  }
}
